import tkinter
import os,time
import pyautogui as pag
import threading
from threading import Lock

exitFlag = 1 #点击启停
lock1 = Lock() #同步锁控制全局变量exitFlag
#桌面程序
win=tkinter.Tk()
win.title("自动点击")
win.geometry("450x200+200+100")#长字母（x）宽  距屏幕左侧位置  距屏幕上边位置
#时间间隔
stime = tkinter.Label(win,text="点击间隔：").place(x=5,y=5)
timevalue = tkinter.StringVar()
timevalue.set('输入时间间隔，单位秒')
timevalue = tkinter.Entry(win, show=None,textvariable=timevalue, font=('Arial', 14))  # 显示成明文形式
timevalue.place(x=100,y=5)
#坐标属性
coord = tkinter.Label(win,text="x坐标：").place(x=5,y=50)
coordvalue =tkinter.StringVar()
coordvalue.set('移动到要点击位置')
coordvalue = tkinter.Entry(win, show=None,textvariable=coordvalue, font=('Arial', 14))  # 显示成明文形式
coordvalue.place(x=100,y=50)
#y坐标属性
ycoord = tkinter.Label(win,text="y坐标：").place(x=5,y=100)
ycoordvalue =tkinter.StringVar()
ycoordvalue.set('移动到要点击位置')
ycoordvalue = tkinter.Entry(win, show=None,textvariable=coordvalue, font=('Arial', 14))  # 显示成明文形式
ycoordvalue.place(x=100,y=100)
#开始方法
def startfunc():
	global lock1
	global exitFlag
	lock1.acquire()
	exitFlag = 1
	lock1.release()
	stimevalue = int(timevalue.get())#循环点击实际
	x = int(coordvalue.get())#点击坐标
	y = int(ycoordvalue.get())#点击坐标
	thread1 = myThread(x,y,stimevalue)#调用线程模块
	thread1.start()#开始线程
#停止方法
	#thread1.join()
def stopfunc():
	#lock1.require()
	global lock1
	global exitFlag
	lock1.acquire()
	exitFlag = 2
	lock1.release()
	print("stop func")
	print(exitFlag)
#获取坐标
def getcoord():
	findnum = 11
	thread2 = xy(findnum)
	thread2.start()
def fondxy(findnum):
	findnum = 10
	while findnum:
		if findnum == 0:
			break
		x,y = pag.position() #返回鼠标的坐标
		coordvalue.delete(0,9)
		coordvalue.insert(0,x)
		ycoordvalue.delete(0,9)
		ycoordvalue.insert(0,y)
		time.sleep(0.6)
		findnum = findnum -1
#开始执行点击事件
#@param x int  桌面x轴坐标
#@param y int  y轴坐标
#@param t int  点击循环时间
def startThread(x,y,t):
	global exitFlag
	while True:
		print(exitFlag)
		if exitFlag == 2:
			print("stop while")
			break
		pag.click(x,y)
		time.sleep(t)
#线程模块
class myThread(threading.Thread):
	def __init__(self, x, y, stimevalue):
		threading.Thread.__init__(self) 
		self.x = x
		self.y = y
		self.stimevalue = stimevalue
	def run(self):
		startThread(self.x, self.y, self.stimevalue)
class xy(threading.Thread):
	def __init__(self,findnum):
		threading.Thread.__init__(self)
		self.findnum = findnum
	def run(self):
		fondxy(self.findnum)
#设置开始停止按钮
btn1 = tkinter.Button(win,text="开始执行",command=startfunc).place(x=100,y=140)
btn2 = tkinter.Button(win,text="结束执行",command=stopfunc).place(x=265,y=140)
btn3 = tkinter.Button(win,text="开始获取位置",command=getcoord).place(x=350,y=50)

win.mainloop()